/**
 * Created by wuji on 2016/11/2.
 */
var $ = require('jquery');
require("easyui");
require('layout/uiJs');
require('layout/util');
var $alert = require('libs/alert');
require('libs/validator');
var timeZoneOffset = require('libs/time-zone-offset');
var $form = require('js-path/formValide.js');
var cookieTimeZone;
require('bootstrap-datetimepicker/locales/bootstrap-datetimepicker.zh-CN');
$(function () {
    var arr,reg=new RegExp("(^| )TimeZone=([^;]*)(;|$)");
    arr = document.cookie.match(reg);
    cookieTimeZone = decodeURI(arr[2]).replace(/\"/g,"");
    $("#add_back").on("click",function () {
        window.history.go(-1);
    });

    //点击“保存”按钮
    // $('#submit_form').on('click',function () {
    //     $("#logisticsPlanForm").submit();
    // });
    //物流产品 select添加数据
    appendOption('api/v1/p/mms/logistics/query',{}
        ,$("#logisticsPlanForm select[name=logisticsId]"));
    //物流线路select添加数据
    $("#logisticsPlanForm select[name=logisticsId]").on("change",function () {
        if(this.value!=''){
            appendOption('api/v1/p/mms/logisticsChannel/query',{logisticsId:this.value}
                ,$("#logisticsPlanForm select[name=channelId]"));
        }
    });
    init();//初始化控件
});

function  init() {
    jugeAdd();
    //表单验证
    formValidationinit();

    $("#logisticsPlanForm").find(".form_date:first").datetimepicker().on(
        "changeDate",function (ev) {
            var $target = $("#logisticsPlanForm").find(".form_date:eq(1)");
            $target.datetimepicker("setDate",ev.date);
            $target.find('input').data('utc0',timeZoneOffset(ev.date,cookieTimeZone))
        }
    );

    $("#logisticsPlanForm").find(".form_datetime:eq(2)").datetimepicker().on(
        "changeDate",function (ev) {
            var $target = $("#logisticsPlanForm").find(".form_datetime:eq(3)");
            $target.datetimepicker("setDate",ev.date);
            $target.find('input').data('utc0',timeZoneOffset(ev.date,cookieTimeZone));
    })
}

//表单验证初始化
function  formValidationinit() {
    $form({ selector: '#logisticsPlanForm'},{
        logisticsId:{required:true},
        channelId:{required:true},
        startPort:{required:true,hasSpecial:true},
        transferPort:{hasSpecial:true},
        destPort:{required:true,hasSpecial:true},
        actualCarrier:{hasSpecial:true},
        voyageNo:{hasSpecial:true},
        estimateLeaveDt:{required:true},
        estimateArriveDt:{required:true},
        tLastOrderDt:{required:true},
        tLastCollectDt:{required:true},
        lastOrderDt:{required:true},
        lastCollectDt:{required:true}
    },{
        logisticsId:{required:'国际物流产品为必填项'},
        channelId:{required:'国际物流线路为必填'},
        startPort:{required:'起运港为必填'},
        destPort:{required:'目的港为必填'},
        estimateLeaveDt:{required:'预计离港日期为必填'},
        estimateArriveDt:{required:'预计到港日期为必填'},
        tLastOrderDt:{required:'截单时间为必填'},
        tLastCollectDt:{required:'截货时间为必填'},
        lastOrderDt:{required:'下入库单最迟时间为必填'},
        lastCollectDt:{required:'企业最迟送货时间为必填'}
    },asyfun,function (data) {
        debugger
        if(data.code == 200){
            $alert("物流计划新增成功");
            window.location.href='Logistics-plan-list';
        }else{
            $alert(data.message);
        }
    });
}
//组装数据
function asyfun() {
    var json = $('#logisticsPlanForm').serializeObject();
    var date1 = $('#data1').data('utc0');
    var date2 = $('#data2').data('utc0');
    var date5 = $('#data6').data('utc0');
    var date6 = $('#data5').data('utc0');
    json.estimateLeaveDt = date1;
    if(date2){
        json.estimateArriveDt = date2;
    }else{
        json.estimateArriveDt = date1;
    }
    json.tLastOrderDt = $('#data3').data('utc0');
    json.tLastCollectDt = $('#data4').data('utc0');
    json.lastCollectDt = date5;
    if(date6){
        json.lastOrderDt = date6;
    }else{
        json.lastOrderDt = date5;
    }
    return json;
}

//判断url是否为新增
function jugeAdd() {
    var href = window.location.href;
    var $form = $('#logisticsPlanForm');
    if(href.indexOf('id=')>0){
        var id =$.getUrlParam('id');
        $form.attr('action','api/v1/p/mms/logisticsChannelPlan/update');
        queryPlan(id);
        $("span.name").html('物流计划修改');
        $("#submit_form").html("确认修改");
    }else{
        $("span.name").html('物流计划新增');
        $form.attr('action','api/v1/p/mms/logisticsChannelPlan/create');
    }
}
//查询数据
function queryPlan(id) {
    $.ajax({
        url:'api/v1/p/mms/logisticsChannelPlan/detail',
        type:'post',
        data:{
            id:id,
        },
        dataType:'json',
        success:function (result) {
            if(result.code == 200){
                appendDate(result.data);
                // $('#goodsAdd_form input[name=code]').rules('remove',"remote");
            }else{
                $alert(result.message);
            }
        },
        error:function (e) {
            $alert('加载数据失败！');
        }
    })
}

//添加数据
function appendDate(data) {
    //物流产品 select添加数据
    appendOption('api/v1/p/mms/logistics/query',{},$("#logisticsPlanForm select[name=logisticsId]"),data.logisticsId);
    //物流线路select添加数据
    appendOption('api/v1/p/mms/logisticsChannel/query',{logisticsId:data.logisticsId},$("#logisticsPlanForm select[name=channelId]"),data.channelId);
    $("#logisticsPlanForm input[name=id]").val(data.id);
    $("#logisticsPlanForm input[name=startPort]").val(data.startPort);
    $("#logisticsPlanForm input[name=transferPort]").val(data.transferPort);
    $("#logisticsPlanForm input[name=destPort]").val(data.destPort);
    $("#logisticsPlanForm input[name=actualCarrier]").val(data.actualCarrier );
    $("#logisticsPlanForm input[name=voyageNo]").val(data.voyageNo);
    var arr,reg=new RegExp("(^| )TimeZone=([^;]*)(;|$)");
    arr = document.cookie.match(reg);
    var cookieTimeZone = decodeURI(arr[2]).replace(/\"/g,"");
    $("#logisticsPlanForm input[name=estimateLeaveDt]").val(new Date(data.estimateLeaveDt.replace(/-/g,"/")).format('yyyy-MM-dd'))
        .data('utc0',timeZoneOffset(new Date(data.estimateLeaveDt.replace(/-/g,"/")),cookieTimeZone));
    $("#logisticsPlanForm input[name=estimateArriveDt]").val(new Date(data.estimateArriveDt.replace(/-/g,"/")).format('yyyy-MM-dd'))
        .data('utc0',timeZoneOffset(new Date(data.estimateArriveDt.replace(/-/g,"/")),cookieTimeZone));
    $("#logisticsPlanForm input[name=tLastOrderDt]").val(new Date(data.tLastOrderDt.replace(/-/g,"/")).format('yyyy-MM-dd hh:mm'))
        .data('utc0',timeZoneOffset(new Date(data.tLastOrderDt.replace(/-/g,"/")),cookieTimeZone));
    $("#logisticsPlanForm input[name=tLastCollectDt ]").val(new Date(data.tLastCollectDt.replace(/-/g,"/")).format('yyyy-MM-dd hh:mm'))
        .data('utc0',timeZoneOffset(new Date(data.tLastCollectDt.replace(/-/g,"/")),cookieTimeZone));
    $("#logisticsPlanForm input[name=lastOrderDt ]").val(new Date(data.lastOrderDt.replace(/-/g,"/")).format('yyyy-MM-dd hh:mm'))
        .data('utc0',timeZoneOffset(new Date(data.lastOrderDt.replace(/-/g,"/")),cookieTimeZone));
    $("#logisticsPlanForm input[name=lastCollectDt ]").val(new Date(data.lastCollectDt.replace(/-/g,"/")).format('yyyy-MM-dd hh:mm'))
        .data('utc0',timeZoneOffset(new Date(data.lastCollectDt.replace(/-/g,"/")),cookieTimeZone));
    $("#logisticsPlanForm input[name=memo ]").val(data.memo );

}
//添加参数
function appendOption(url,data,$select,value) {
    $.ajax({
        url:url,
        type:'post',
        data:data,
        dataType:'json',
        success:function (result) {
            if(result.code==200){
                var options =  '<option value="">请选择</option>';
                $.each(result.data,function (index,obj) {
                    var checked = "";
                    if(value){
                        if(value ==obj.warehouseId|| value ==obj.logisticsId|| value ==obj.id){
                            checked = "selected"
                        }
                    }
                    if(obj.warehouseId !=undefined){
                        options += "<option value='" + obj.warehouseId + "' "+checked+">" + obj.warehouseName + "</option>";
                    }else if(obj.id!=undefined){
                        if(obj.name != undefined){
                            options += "<option value='" + obj.id + "' "+checked+">" + obj.name + "</option>";
                        }else{
                            options += "<option value='" + obj.id + "' "+checked+">" + obj.nameCn  + "</option>";
                        }
                    }else {
                        options += "<option value='" + obj.logisticsId  + "' "+checked+">" + obj.name + "</option>";
                    }
                });
                $select.empty();
                $select.append(options);
            }else{
                var span = '<span  class="error-info"><span class="glyphicon glyphicon-remove"></span>'+
                    result.data.message+'</span>';
                $select.parent('div').next('div.col-xs-3').append(span);
            }
        },
        error:function (e) {
            console.log(url+'接口错误');
        }
    })
}